﻿using Mapster;
using SqlSugar;
using Zhp.Common.Appsetting;
using Zhp.Common.Helper;
using Zhp.Common.WebApp;
using Zhp.Entity.Sys;
using Zhp.IService.Sys;
using Zhp.Model.Sys;
using Zhp.Service.Base;
using Zhp.SqlSugar.Repository;

namespace Zhp.Service.Sys
{
    public class SysUserService : BaseService<SysUser>, ISysUserService
    {

        public SysUserService(ICurrentUser currentUser, IBaseRepository<SysUser> rep)
        {
            _currentUser = currentUser;
            _rep = rep;
        }

        public async Task<List<UserModel>> GetUser(UserQuery query)
        {
            var userList = await _rep.GetPageListAsync(new List<IConditionalModel>
            {
                new ConditionalModel
                {
                    FieldName = "UserName",
                    ConditionalType = ConditionalType.NoEqual,
                    FieldValue = "root"
                }
            }, query, x => x.CreateTime, OrderByType.Desc);

            return userList.Adapt<List<UserModel>>();
        }

        public async Task<bool> Create(UserCreate create)
        {
            var user = create.Adapt<SysUser>();

            var options = AppSettingHelper.GetOptions<SysDataOptions>();
            user.Password = options.DefaultPassword.ToSHA256String();

            return await _rep.InsertAsync(user);
        }

        public async Task<bool> Update(UserCreate update)
        {
            var user = await _rep.GetByIdAsync(update.Id);

            if (user != null)
            {
                update.Adapt(user);

                return await _rep.UpdateAsync(user);
            }

            return false;
        }

        public async Task<bool> Delete(string id)
        {
            return await _rep.DeleteByIdAsync(id);
        }

        public async Task<bool> ResetPassword(long id)
        {
            var user = await _rep.GetByIdAsync(id);
            var options = AppSettingHelper.GetOptions<SysDataOptions>();
            user.Password = options.DefaultPassword.ToSHA256String();
            user.PasswordReSetTime = DateTime.Now;
            return await _rep.UpdateAsync(user);
        }

        public async Task<SysUser> QueryByName(string name)
        {
            return await _rep.GetFirstAsync(x => x.UserName == name && x.IsEnabled);
        }
    }
}
